// 竞赛相关JavaScript功能
document.addEventListener('DOMContentLoaded', function() {
    // 加载竞赛数据
    loadCompetitions();
    
    // 统计卡片点击筛选：进行中 / 即将开始
    const statusFilter = document.getElementById('statusFilter');
    const activeStatNumber = document.getElementById('activeCompetitions');
    const upcomingStatNumber = document.getElementById('upcomingCompetitions');
    
    const attachFilterHandler = (element, statusValue) => {
        if (!element) return;
        const card = element.closest('.stat-card') || element;
        if (card) {
            card.style.cursor = 'pointer';
            card.addEventListener('click', function() {
                if (statusFilter) {
                    statusFilter.value = statusValue;
                    performSearch();
                }
            });
        }
    };
    
    attachFilterHandler(activeStatNumber, 'ongoing');
    attachFilterHandler(upcomingStatNumber, 'upcoming');
    
    // 添加排序功能的事件监听
    const sortFilter = document.getElementById('sortFilter');
    if (sortFilter) {
        sortFilter.addEventListener('change', function() {
            performSearch();
        });
    }
});

// 加载竞赛数据
function loadCompetitions(apiUrl = '/api/competitions') {
    const container = document.getElementById('competitions-container');
    const loading = document.getElementById('loading');
    const noResults = document.getElementById('no-results');
    const sortFilter = document.getElementById('sortFilter');
    
    if (!container) return;
    
    // 显示加载状态
    if (loading) loading.style.display = 'block';
    if (noResults) noResults.style.display = 'none';
    container.innerHTML = '';
    
    fetch(apiUrl)
        .then(response => response.json())
        .then(data => {
            if (loading) loading.style.display = 'none';
            
            if (Array.isArray(data) && data.length > 0) {
                // 获取当前排序类型
                const sortType = sortFilter ? sortFilter.value : '';
                
                // 对数据进行排序
                const sortedData = sortCompetitions(data, sortType);
                
                renderCompetitions(sortedData);
                updateCompetitionStats(sortedData);
            } else {
                if (noResults) noResults.style.display = 'block';
            }
        })
        .catch(error => {
            console.error('加载竞赛数据错误:', error);
            if (loading) loading.style.display = 'none';
            if (noResults) noResults.style.display = 'block';
        });
}

// 渲染竞赛卡片
function renderCompetitions(competitions) {
    const container = document.getElementById('competitions-container');
    if (!container) return;
    
    container.innerHTML = '';
    
    competitions.forEach(competition => {
        const card = createCompetitionCard(competition);
        container.appendChild(card);
    });
}

// 创建竞赛卡片
function createCompetitionCard(competition) {
    const card = document.createElement('div');
    card.className = 'contest-card';
    card.dataset.id = competition.id;
    
    // 获取评级徽章类名和显示文本
    const badgeInfo = getBadgeClassAndText(competition.rating);
    const badgeClass = badgeInfo.badgeClass;
    const ratingText = badgeInfo.ratingText;
    
    // 格式化日期
    const startDate = formatDate(competition.start_date);
    const endDate = formatDate(competition.end_date);
    
    // 创建图片元素，支持加载失败时的回退
    const imgElement = document.createElement('img');
    imgElement.className = 'card-image';
    imgElement.alt = competition.name;
    imgElement.loading = 'lazy';
    
    // 设置图片源，优先使用competition.json中的image_url
    if (competition.image_url && competition.image_url.trim() !== '') {
        imgElement.src = competition.image_url;
        // 图片加载失败时的处理
        imgElement.onerror = function() {
            this.style.display = 'none';
        };
    } else {
        // 如果没有image_url或为空，隐藏图片元素并添加无图片样式
        imgElement.style.display = 'none';
    }
    
    // 生成随机背景渐变的函数
    const getRandomGradient = () => {
        const gradients = [
            'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
            'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
            'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
            'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
            'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
            'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
            'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)',
            'linear-gradient(135deg, #a8caba 0%, #5d4e75 100%)',
            'linear-gradient(135deg, #d299c2 0%, #fef9d7 100%)'
        ];
        return gradients[Math.floor(Math.random() * gradients.length)];
    };
    
    card.innerHTML = `
        <div class="card-image"></div>
        <span class="card-badge ${badgeClass}">${ratingText}</span>
        <div class="card-content">
            <div class="card-title">${competition.name}</div>
            <div class="card-description">${competition.description}</div>
            <div class="card-info-row">
                <div class="card-categories">
                    ${competition.categories.map(category => `<span class="category-tag">${category}</span>`).join('')}
                </div>
                <div class="card-organizer">${competition.organizer}</div>
            </div>
            <div class="card-footer">
                <span>报名截止: ${endDate}</span>
                <span>热度: ${getCompetitionPopularity(competition)}</span>
            </div>
        </div>
    `;
    
    // 设置图片或背景
    const imageElement = card.querySelector('.card-image');
    if (competition.image_url && competition.image_url.trim() !== '') {
        // 有图片时设置为背景图片
        imageElement.style.backgroundImage = `url(${competition.image_url})`;
        imageElement.style.backgroundSize = 'cover';
        imageElement.style.backgroundPosition = 'center';
        imageElement.style.backgroundRepeat = 'no-repeat';
    } else {
        // 没有图片时设置随机渐变背景
        imageElement.style.background = getRandomGradient();
        imageElement.style.backgroundSize = 'cover';
        imageElement.style.backgroundPosition = 'center';
    }
    
    // 添加点击事件 - 显示详情
    card.addEventListener('click', function(e) {
        // 显示竞赛详情
        if (window.showCompetitionDetail) {
            window.showCompetitionDetail(competition);
        }
    });
    
    return card;
}

// 使用全局版本
const getBadgeClassAndText = window.getBadgeClassAndText;
const getBadgeClass = (rating) => window.getBadgeClassAndText(rating).badgeClass;
const formatDate = window.formatDate;

// 更新竞赛统计信息
function updateCompetitionStats(competitions) {
    const totalElement = document.getElementById('totalCompetitions');
    const activeElement = document.getElementById('activeCompetitions');
    const upcomingElement = document.getElementById('upcomingCompetitions');
    
    if (totalElement) totalElement.textContent = competitions.length;
    
    const now = new Date();
    let activeCount = 0;
    let upcomingCount = 0;
    
    competitions.forEach(competition => {
        const startDate = new Date(competition.start_date);
        const endDate = new Date(competition.end_date);
        
        if (now >= startDate && now <= endDate) {
            activeCount++;
        } else if (now < startDate) {
            upcomingCount++;
        }
    });
    
    if (activeElement) activeElement.textContent = activeCount;
    if (upcomingElement) upcomingElement.textContent = upcomingCount;
}



// 获取状态文本
function getStatusText(status) {
    switch (status) {
        case 'ongoing':
            return '进行中';
        case 'upcoming':
            return '即将开始';
        case 'finished':
            return '已结束';
        default:
            return '未知状态';
    }
}

// 复制竞赛详细信息
function copyCompetitionDetail(competitionName, detail) { if (typeof window.copyCompetitionDetail === 'function') window.copyCompetitionDetail(competitionName, detail); }

// 回退复制方法
function fallbackCopyTextToClipboard(text) { if (typeof window.fallbackCopyTextToClipboard === 'function') window.fallbackCopyTextToClipboard(text); }

// 显示复制成功提示
function showCopySuccess() { if (typeof window.showCopySuccess === 'function') window.showCopySuccess(); }

// 显示复制失败提示
function showCopyError() { if (typeof window.showCopyError === 'function') window.showCopyError(); }

// 执行搜索和筛选功能
function performSearch() {
    const searchInput = document.getElementById('searchInput');
    const categoryFilter = document.getElementById('categoryFilter');
    const statusFilter = document.getElementById('statusFilter');
    const sortFilter = document.getElementById('sortFilter');
    
    const query = searchInput ? searchInput.value : '';
    const category = categoryFilter ? categoryFilter.value : '';
    const status = statusFilter ? statusFilter.value : '';
    const sort = sortFilter ? sortFilter.value : '';
    
    // 构建查询参数
    const params = new URLSearchParams();
    if (query) params.append('q', query);
    if (category) params.append('category', category);
    if (status) params.append('status', status);
    if (sort) params.append('sort', sort);
    
    // 重新加载竞赛数据
    loadCompetitions(`/api/competitions/search?${params.toString()}`);
}

// 排序竞赛数据
function sortCompetitions(competitions, sortType) {
    if (!sortType || !competitions || competitions.length === 0) {
        return competitions;
    }
    
    const sortedCompetitions = [...competitions];
    
    switch (sortType) {
        case 'popularity_desc':
            // 热度最高
            sortedCompetitions.sort((a, b) => {
                const popularityA = getCompetitionPopularity(a);
                const popularityB = getCompetitionPopularity(b);
                return popularityB - popularityA;
            });
            break;
            
        case 'popularity_asc':
            // 热度最低
            sortedCompetitions.sort((a, b) => {
                const popularityA = getCompetitionPopularity(a);
                const popularityB = getCompetitionPopularity(b);
                return popularityA - popularityB;
            });
            break;
            
        case 'start_date_asc':
            // 开始时间最早
            sortedCompetitions.sort((a, b) => new Date(a.start_date) - new Date(b.start_date));
            break;
            
        case 'start_date_desc':
            // 开始时间最晚
            sortedCompetitions.sort((a, b) => new Date(b.start_date) - new Date(a.start_date));
            break;
            
        case 'end_date_asc':
            // 结束时间最早
            sortedCompetitions.sort((a, b) => new Date(a.end_date) - new Date(b.end_date));
            break;
            
        case 'end_date_desc':
            // 结束时间最晚
            sortedCompetitions.sort((a, b) => new Date(b.end_date) - new Date(a.end_date));
            break;
            
        case 'rating_desc':
            // 评级最高
            sortedCompetitions.sort((a, b) => {
                const ratingA = getRatingValue(a.rating);
                const ratingB = getRatingValue(b.rating);
                return ratingB - ratingA;
            });
            break;
            
        case 'rating_asc':
            // 评级最低
            sortedCompetitions.sort((a, b) => {
                const ratingA = getRatingValue(a.rating);
                const ratingB = getRatingValue(b.rating);
                return ratingA - ratingB;
            });
            break;
            
        default:
            // 默认排序：按开始时间升序
            sortedCompetitions.sort((a, b) => new Date(a.start_date) - new Date(b.start_date));
    }
    
    return sortedCompetitions;
}

// 获取评级数值（用于排序）
function getRatingValue(rating) {
    const ratingMap = {
        'A+': 10,
        'A': 9,
        'A-': 8,
        'B+': 7,
        'B': 6,
        'B-': 5,
        'C+': 4,
        'C': 3,
        'C-': 2,
        'D': 1
    };
    return ratingMap[rating] || 0;
}

// 获取竞赛热度值（基于竞赛ID生成固定值，确保排序一致性）
function getCompetitionPopularity(competition) {
    if (competition.popularity !== undefined) {
        return competition.popularity;
    }
    
    // 基于竞赛ID生成固定的热度值
    const id = competition.id || competition.name || '';
    let hash = 0;
    for (let i = 0; i < id.length; i++) {
        const char = id.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // 转换为32位整数
    }
    
    // 生成100-2000之间的热度值
    const popularity = Math.abs(hash) % 1900 + 100;
    
    // 缓存热度值到竞赛对象中
    competition.popularity = popularity;
    
    return popularity;
}